package com.xingshang.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 检查用户是否已登录
        Object user = request.getSession().getAttribute("user");
        if (user == null) {
            // 未登录，重定向到登录页
            response.sendRedirect(request.getContextPath() + "/user/login");
            return false; // 拦截请求，不进入 controller
        }
        return true; // 已登录，放行
    }
}
